package com.bonc.ioc.controller;

import com.bonc.ioc.base.controller.BaseController;
import com.bonc.ioc.common.util.AppReply;
import com.bonc.ioc.model.DataAssetInfo;
import com.bonc.ioc.model.SysDicInfo;
import com.bonc.ioc.service.SysDicInfoService;
import com.bonc.ioc.util.DictionaryEnum;
import com.bonc.ioc.validation.AppAuthAnnotation;
import com.bonc.ioc.vo.SysDicInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 字典
 *
 * @author: wangqinglin
 * @date: 2020/11/6 11:50
 */

@RestController
@RequestMapping("/dic")
@Slf4j
public class DicController extends BaseController {

    @Autowired
    private SysDicInfoService dicService;


    /**
     * 字典中 查看分类
     *
     * @param type
     * @return
     */
    @GetMapping("getByType")
    public AppReply getByType(String type) {
        DictionaryEnum dictionaryEnum = DictionaryEnum.valueOf(type.toUpperCase());
        return new AppReply(AppReply.SUCCESS_CODE, AppReply.SUCCESS_MSG, dicService.getByType(dictionaryEnum.getValue()));
    }

    /**
     * 字典中 查看分类
     *
     * @param
     * @return
     */
    @GetMapping("getDirs")
    public AppReply getDirs() {
        return AppReply.success(dicService.getDirs());
    }


    @PostMapping("/save")
    @AppAuthAnnotation
    public AppReply saveAddictsInfo(@RequestBody SysDicInfoVo item) {
        return AppReply.success(dicService.save(item));
    }


    @GetMapping("/delete")
    @AppAuthAnnotation
    public AppReply deleteMadInfo(@RequestParam String dicId) {
        if("".equals(dicId) || dicId == null){
            return AppReply.error("请选择要删除的目录");
        }
        int num = dicService.deleteByPrimaryKey(dicId);
        if(num < 0){
            return AppReply.error("含有子集");
        }
        return AppReply.success(num);
    }

    /**
     * 查询分类字典
     *
     * @param pid 父id
     * @return pid下的所有字典信息
     * @throws BindException
     */
    @GetMapping("/queryCategory")
    public AppReply queryCategory(Integer pid) throws BindException {
        if (pid == 3){
            List<DataAssetInfo> result1 = dicService.queryDataSource();
            List<SysDicInfo> result = new ArrayList<>();
            for(int i=0;i<result1.size();i++){
                SysDicInfo sysDicInfo = new SysDicInfo();
                sysDicInfo.setDicCode(String.valueOf(result1.get(i).getDataFormat()));
                sysDicInfo.setDicName(result1.get(i).getDataOrigin());
                result.add(sysDicInfo);
            }
            return new AppReply(AppReply.SUCCESS_CODE, "查询成功",result);
        }else {
            List<SysDicInfo> result = dicService.queryCategory(pid);
            return new AppReply(AppReply.SUCCESS_CODE, "查询成功",result);
        }
    }


}
